package com.zhilei.deepseekdoctor.controller;

import com.zhilei.deepseekdoctor.enums.SSEMsgType;
import com.zhilei.deepseekdoctor.utils.SSEServer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * 连接ollama的控制器
 *
 * @author zhilei
 * @version 1.0
 */
@RestController
@RequestMapping("/api/sse")
public class SSEController {

    /**
     * 创建一个新的长连接
     *
     * @param userId 根据哪个用户
     * @return
     */
    @GetMapping(path = "/connect", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter sseClint(@RequestParam String userId) {

        // 自动重连
        return SSEServer.connect(userId);
    }

    /**
     * 发送消息
     *
     * @param userId
     * @param message
     * @return
     */
    @GetMapping(path = "/sendMessage")
    public String sendMessage(@RequestParam String userId, @RequestParam String message) {
        SSEServer.sendMessage(userId, message, SSEMsgType.MESSAGE);
        return "ok";
    }

    /**
     * 群发送消息
     *
     * @param message
     * @return
     */
    @GetMapping(path = "/sendAllMessage")
    public String sendAllMessage(@RequestParam String message) {
        SSEServer.sendMessageToAllUsers(message);
        return "ok";
    }

    /**
     * 群发送消息
     *
     * @param message
     * @return
     */
    @GetMapping(path = "/sendAddMessage")
    public String sendAddMessage(@RequestParam String userId, @RequestParam String message) {
        for (int i = 0; i < 10; i++) {
            SSEServer.sendMessage(userId, message + i, SSEMsgType.ADD);
        }
        return "ok";
    }

    /**
     * 群发送消息
     *
     * @param message
     * @return
     */
    @GetMapping(path = "/sendAddTOAllMessage")
    public String sendAddTOAllMessage(@RequestParam String message) {
        for (int i = 0; i < 10; i++) {
            SSEServer.sendMessageAddToAllUsers(message + i);
        }
        return "ok";
    }

    /**
     * 切换用户的长连接
     *
     * @param userId
     * @return
     */
    @GetMapping(path = "/stopServer")
    public String stopServer(@RequestParam String userId) {
        SSEServer.stopServer(userId);
        return "ok";
    }

    /**
     * 获得当前所有的会话总连接数（在线人数）
     *
     * @return
     */
    @GetMapping(path = "/getOnlineCounts")
    public Integer getOnlineCounts() {
        return SSEServer.getOnlineCounts();
    }

}
